﻿using System.Linq;
using Microsoft.AspNetCore.Mvc.Filters;

namespace SingleBlog.UI.Filters
{
    using Core.Services;
    using Microsoft.AspNetCore.Mvc;

    /// <summary>
    /// 表示站点关闭的过滤器。
    /// </summary>
    /// <seealso cref="IAuthorizationFilter" />
    public class SiteCloseAttribute:IAuthorizationFilter
    {
        /// <summary>
        /// 排除的页面名称配置。
        /// </summary>
        static readonly string[] filterPages = new[] { "Close", "Error" };

        private readonly SettingService _settingService;
        /// <summary>
        /// 初始化 <see cref="SiteCloseAttribute"/> 类的新实例。
        /// </summary>
        /// <param name="settingService">注入的 <see cref="SettingService"/> 实例。</param>
        public SiteCloseAttribute(SettingService settingService)
        {
            _settingService = settingService;
        }

        /// <summary>
        /// Called early in the filter pipeline to confirm request is authorized.
        /// </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext" />.</param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //管理员不受此限制
            if (context.HttpContext.User.Identity.IsAuthenticated && context.HttpContext.User.IsInRole("Administrator"))
            {
                return;
            }

            //这里要修改
            if (context.RouteData.Values.TryGetValue("page", out object value) && _settingService.GetGeneralSetting().IsClosed)
            {
                if (filterPages.Contains(value.ToString().TrimStart('/')))
                {
                    return;
                }

                context.Result = new RedirectResult("/Close");
                return;
            }
        }
        
    }
}
